<?php

namespace App\Http\Controllers;

use App\Models\Doctor;
use App\User;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Easemob;

class SurveysController extends BaseController
{
    public $host = "https://open.wj.qq.com";
    public $wj = "https://wj.qq.com";

    /***
     * @return mixed
     * 获取token
     */
    private function getAccessToken()
    {
        $token = Redis::get("surveys_access_token");
        if ($token) {
            return $token;
        }
        $url = $this->host . "/api/oauth2/access_token?appid=" . config("omnipay.Surveys.App_ID") . "&secret=" . config("omnipay.Surveys.App_Secret") . "&grant_type=client_credential";
        $res = (new Easemob())->postCurl($url, "", [], "GET");
        if ($res['code'] == "OK") {
            Redis::setex("surveys_access_token", $res['data']['expires_in'], $res['data']['access_token']);
            return $res['data']['access_token'];
        } else {
            return $res;
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 注册账号
     */
    public function register($param)
    {
//        $param = $request->input();
        $token = self::getAccessToken();
        $openid = Tool::getOpenid($param);
        $url = $this->host . "/api/sso/users?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . $token;
        $users = $this->getUserInfo($param);
        $options = array(
            "openid" => $openid,
            "nickname" =>$users->phone,
            "avatar" => Url::getHttpHost() . 'image/hd.png'
        );
        $body = json_encode($options);
        $res = (new Easemob())->postCurl($url, $body, [], "POST");
        if ($res['code'] == "OK") {
            $survey_uid = $res['data']['user_id'];
            if ($param['type'] == 1) {
                $info = (new User())->where([['id', '=', $param['user_id']]])->first();
                if (empty($info->survey_uid)) {
                    (new User())->where([['id', '=', $param['user_id']]])->update(['survey_uid' => $survey_uid]);
                }
            } else {
                $info = (new Doctor())->where([['id', '=', $param['user_id']]])->first();
                if (empty($info->survey_uid)) {
                    (new Doctor())->where([['id', '=', $param['user_id']]])->update(['survey_uid' => $survey_uid]);
                }
                $this->addUsertoGroup($param);//添加团队中
                $this->addGroupShare($info->survey_uid);//添加到共享组
            }
            return $this->ResultJson(1, '注册成功!', []);
        }
        return $this->ResultJson(0, '注册失败!', []);
    }

    /**
     * @param $data
     * 一次性登录
     */
    public function getOneTimesLoginCode($data)
    {
        $token = self::getAccessToken();
        $url = $this->host . "/api/sso/code?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . $token;
        if ($data['type'] == 1) {
            $survey_uid = (new User())->where([['id', '=', $data['user_id']]])->value("survey_uid");
            $options = array(
                "user_id" => (int)$survey_uid,
                "scene_type" => "respondent"
            );
        } else {
            $survey_uid = (new Doctor())->where([['id', '=', $data['user_id']]])->value("survey_uid");
            $options = array(
                "user_id" => (int)$survey_uid,
                "scene_type" => "user"
            );
        }
        $body = json_encode($options);
        $res = (new Easemob())->postCurl($url, $body, [], 'POST');
        if ($res['code'] == "OK") {
            return $res['data']['code'];
        } else {
            return $res;
        }
    }

    /**
     * @param Request $request
     * 添加人员到共享项目组
     */
    public function addGroupShare($survey_uid)
    {
        $url = $this->host . "/api/orgs/" . config("omnipay.Surveys.Group_Id") . "/projects/" . config("omnipay.Surveys.Parent_Id") . "/members?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . self::getAccessToken();
        $options = array(
            "members" => array(
                array(
                    "user_id" => (int)$survey_uid,
                    "role" => 2
                )
            )
        );
        $body = json_encode($options);
        $res = (new Easemob())->postCurl($url, $body, [], "POST");
        if ($res['code'] == "OK") {
            return true;
        }
    }


    /**
     * 获取共享项目组列表
     */
    public function getGroupShareProject()
    {
        $url = $this->host . "/api/orgs/" . config("omnipay.Surveys.Group_Id") . "/projects?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . self::getAccessToken();
        $data = (new Easemob())->postCurl($url, "", [], "GET");
        dd($data);
    }






    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 获取跳转链接
     */
    public function getToAbility(Request $request)
    {
        $param = $request->input();
        $code = self::getOneTimesLoginCode($param);
        $appid = config("omnipay.Surveys.App_ID");
        $action = $param['ability'];
        $group_id = config("omnipay.Surveys.Group_Id");
        switch ($action){
            case 'my_surveys':
                // 个人问卷列表页
                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}";
                break;
            case 'org_surveys':
                // 团队问卷列表页
                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}&org_id={$group_id}";
                break;
            case 'survey_create':
                // 重定向到腾讯问卷创建页面
                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}";
                break;
            case 'org_survey_create':
                //创建团队问卷
                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}&org_id={$group_id}";
                break;
            case 'org_survey_create_in_project':
                //创建团队问卷
                (int)$parent_id =  config("omnipay.Surveys.Parent_Id");
                $url = "https://wj.qq.com/api/v2/redirect?appid={$appid}&action={$action}&org_id={$group_id}&project_id={$parent_id}&code={$code}";
//                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}&org_id={$group_id}&parent_id={$parent_id}";
//                echo $url;die;
                break;
            case 'survey_collect':
                if(!isset($param['url']) && empty($param['url'])){
                    return $this->ResultJson(0, '!', []);
                }
                $suy_url = $param['url'];
                $arr = explode('/', trim($suy_url,'/'));
                $survey_hash =$arr['5'];
                $survey_id = $arr['4'];
                // 重定向到腾讯问卷填答页面
//                $survey_id = 0; // 从问卷投放链接获得
//                $survey_hash = "abcd";
                $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}&survey_id={$survey_id}&survey_hash={$survey_hash}";
                break;
            default:
                echo "unknown action";
                exit();
        }
        return $this->ResultJson(1, '获取成功!', ['url'=>$url]);
    }

    /**
     * @param $param
     * @return string处理用户问卷访问链接
     */
    public function handelUserCheakUrl(Request $request)
    {
        $param = $request->input();
        $code = self::getOneTimesLoginCode($param);
        $appid = config("omnipay.Surveys.App_ID");
        $action = "survey_collect";
        $suy_url = $param['url'];
        $arr = explode('/', trim($suy_url, '/'));
        $survey_hash = $arr['5'];
        $survey_id = $arr['4'];
        // 重定向到腾讯问卷填答页面
        $url = $this->wj . "/api/v2/redirect?appid={$appid}&code={$code}&action={$action}&survey_id={$survey_id}&survey_hash={$survey_hash}";
        header('Location: ' . $url);
    }

    /**
     * @return mixed
     * 获取团队信息
     */
    private function getGroupInfo()
    {
        $url = $this->host . "/api/orgs/" . config("omnipay.Surveys.Group_Id") . "?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . self::getAccessToken();
        $red = (new Easemob())->postCurl($url, "", [], 'GET');
        return $red['data'];
    }

    /**
     * @return mixed
     * 获取小组列表
     */
    private function getTeamList($team_id)
    {
        $url = $this->host ."/api/contacts/teams/".(int)$team_id."/groups?appid=". config("omnipay.Surveys.App_ID") ."&access_token=". self::getAccessToken();
        //        $url = $this->host . "/api/orgs/" . config("omnipay.Surveys.Group_Id") . "?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . self::getAccessToken();
        $red = (new Easemob())->postCurl($url, "", [], 'GET');
        return $red['data'];
    }



    private function getUserInfo($data)
    {
        if ($data['type'] == 1) {
            return (new User())->where([['id', '=', $data['user_id']]])->first();
        } else {
            return (new Doctor())->where([['id', '=', $data['user_id']]])->first();
        }
    }

    /**
     * @param Request $request
     * 将成员添加到组中
     */
    public function addUsertoGroup($data)
    {
//        $group = self::getGroupInfo();
//        $team_list = self::getTeamList($group['team_id']);
        $user = self::getUserInfo($data);
        $url = $this->host . "/api/contacts/teams/" .(int)config("omnipay.Surveys.Group_Team_Id") . "/groups/" . (int)config("omnipay.Surveys.Teams_Id") . "/users/" . (int)$user->survey_uid . "?appid=" . config("omnipay.Surveys.App_ID") . "&access_token=" . self::getAccessToken();
        $options = array(
            "openid" => $user->open_id,
            "role" => 3
        );
        $body = json_encode($options);
        $red = (new Easemob())->postCurl($url, $body, [], 'POST');
        if ($red['code'] == "OK") {
            return true;
        } else {
            return false;
        }
    }
    
    
    /**
     *
     * 获取用户问卷列表
     */
    public function getSurveys(Request $request)
    {
        $param = $request->input();
        if(!isset($param['user_id'])){
            return $this->ResultJson(0, '用户ID不能为空!',[]);
        }
        if(!isset($param['user_id'])){
            return $this->ResultJson(0, '用户ID不能为空!',[]);
        }

        
    }






}
